package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;


    private static Long getCurrentUserId() {
        /*获取用户信息*/
        UserDTO currentUser = (UserDTO) ThreadLocalUtil.get();
        Long currentUserId = currentUser.getId();
        if (currentUserId == null) {
            return null;
        }
        return currentUserId;
    }

    @Override
    public Result likeBlog(Long id) {
        //获取当前登录用户id
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return Result.fail("请先登录");
        }
        //根据博文id查询出对应的Blog对象
        Blog blog = query().eq("id", id).one();
        if (blog == null) {
            return Result.fail("博文不存在");
        }
        //基于redis的set集合判断用户是否已经点赞
        String key = BLOG_LIKED_KEY + "_" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, currentUserId.toString());

        if (score == null) {
            //如果用户没有点赞过，则进行点赞
            // 3.1 修改点赞数量+1
            boolean update = update()
                    .setSql("liked = liked + 1").eq("id", id).update();
            //3.2 将已经点赞过的用户id存入redis的set集合中
            if (update) {
                stringRedisTemplate.opsForZSet().add(key, currentUserId.toString(), Instant.now().toEpochMilli());
            }
            //3.3将Blog对象的isLiked属性设置为true
            blog.setIsLike(true);
            //3.4响应结果
            return Result.ok(blog);
        } else {
            //如果用户已经点赞过，则取消点赞
            // 4.1 修改点赞数量-1
            boolean update = update()
                    .setSql("liked = liked - 1").eq("id", id).update();
            //4.2 将已经点赞过的用户id从redis的set集合中移除
            if (update) {
                stringRedisTemplate.opsForZSet().remove(key, currentUserId.toString());
            }
            //4.3 将Blog对象的isLiked属性设置为false
            blog.setIsLike(false);
            //4.4 响应结果
            return Result.ok(blog);
        }
    }

    @Override
    public Result queryMyBlog(Integer current) {
        // 获取登录用户
        UserDTO userDTO = ThreadLocalUtil.get();
        // 根据用户查询
        Page<Blog> page = query()
                .eq("user_id", userDTO.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            //查询用户信息并设置到博客对象中
            queryBlogUserAndSetToBlog(blog);
            // 查询blog是否被当前登录用户点赞,设置到博客对象中
            boolean isBlogLiked = isBlogLiked(blog);
            if (isBlogLiked) {
                // 将isLiked设置为true
                blog.setIsLike(true);
            } else {
                // 将isLiked设置为false
                blog.setIsLike(false);
            }
        });
        return Result.ok(records);
    }

    private void queryBlogUserAndSetToBlog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryBlogByUserId(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn("无效的博文id：id={}", id);
            return Result.fail("无效的博文id");
        }

        try {
            // 2. 查询博文
            Blog blog = getById(id); // 使用getById代替query().eq()，更高效且直观
            if (blog == null) {
                log.error("博文不存在：id={}", maskId(id)); // 对敏感信息进行脱敏处理
                return Result.fail("博文不存在");
            }

            // 3. 查询用户信息并设置到博客对象中
            User user = userService.getById(blog.getUserId());
            if (user == null) {
                log.error("用户不存在：userId={}", blog.getUserId());
                return Result.fail("用户不存在");
            }
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            //5. 查询blog是否被当前登录用户点赞
            boolean isBlogLiked = isBlogLiked(blog);
            if (isBlogLiked) {
                // 将isLiked设置为true
                blog.setIsLike(true);
            } else {
                // 将isLiked设置为false
                blog.setIsLike(false);
            }
            // 4. 响应结果
            return Result.ok(blog);
        } catch (Exception e) {
            log.error("查询博文失败：id={}", maskId(id), e);
            return Result.fail("系统错误");
        }
    }

    /**
     * 根据博文id查询点赞用户排行版前5的用户信息
     *
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        //业务健壮性判断
        if (id == null || id <= 0) {
            log.warn("无效的博文id：id={}", id);
            return Result.fail("无效的博文id");
        }
        //1. 从redis缓存中查询点赞用户排行版前5的用户信息
        //1.1根据id查询博文
        Blog blog = getById(id);
        if (blog == null) {
            log.error("博文不存在：id={}", maskId(id));
            return Result.fail("博文不存在");
        }
        //1.2从redis缓存中查询点赞用户排行版前5的用户信息
        String key = BLOG_LIKED_KEY + "_" + blog.getId();
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //1.3转换为Set<long>
        List<Long> userIds = range.stream().map(userId -> Long.parseLong(userId)).collect(Collectors.toList());
        //1.5转换为Set<UserDTO>
        List<UserDTO> userDTOs = new ArrayList<>();
        userIds.stream().forEach(userId -> {
            User user = userService.query().eq("id", userId).one();
            UserDTO userDTO = BeanUtil.toBean(user, UserDTO.class);//转换为UserDTO
            userDTOs.add(userDTO);
        });
        //反转集合，使得排行版从高到低
        Collections.reverse(userDTOs);
        //1.4根据userIds查询用户信息
        if (userDTOs.isEmpty()) {//如果用户信息为空，则返回空集合
            return Result.ok(Collections.emptyList());
        }
        //1.5响应结果
        return Result.ok(userDTOs);
    }

    @Override
    public Result saveBlog(Blog blog) {
        try {
            //1. 获取登录用户
            Long currentUserId = getCurrentUserId();
            if (currentUserId == null) {
                return Result.fail("请先登录");
            }

            blog.setUserId(currentUserId);

            //2. 保存探店博文
            boolean save = save(blog);
            if (!save) {
                log.error("保存blog失败：{}", blog);
                return Result.fail("发布blog失败");
            }

            //3. 查询笔记作者的所有粉丝 并推送消息给所有粉丝
            //3.1 查询所有粉丝关注博主的关注对象列表
            List<Follow> fanUserFollows = followService.query().eq("follow_user_id", currentUserId).list();

            //3.2 推送消息给所有粉丝
            for (Follow fanUserFollow : fanUserFollows) {
                Long fanUserId = fanUserFollow.getUserId();
                String key = FEED_MESSAGE_KEY_PREFIX + fanUserId; // 每个粉丝的收信箱的key

                // 推送消息
                Boolean added = stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
                if (Boolean.TRUE.equals(added)) {
                    log.info("推送消息给粉丝：fanUserId={}, blogId={}", fanUserId, blog.getId());
                } else {
                    log.error("推送消息给粉丝失败：fanUserId={}, blogId={}", fanUserId, blog.getId());
                    // 这里可以选择是否中断操作或者记录失败的粉丝id，视业务需求而定
                }
            }

            // 返回id
            return Result.ok(blog.getId());
        } catch (Exception e) {
            log.error("保存Blog并推送消息过程中发生异常：", e);
            return Result.fail("系统错误");
        }
    }

    private static final String FEED_MESSAGE_KEY_PREFIX = "blog_feed:";

    @Override
    public Result queryBlogFollow(Long maxTimeStamp, Integer offset) {
        //1.获取当前登录用户
        Long currentUserId = getCurrentUserId();
        //2.读取有自己关注的博主的推文的收信箱(redis的在ZSET集合(blogId,timeStamp);
        String key = FEED_MESSAGE_KEY_PREFIX + currentUserId;
        //3.获取Zset的元组集合,包含blogId和timeStamp
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, maxTimeStamp.doubleValue(), offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            log.warn("没有新的推文");
            return Result.ok();
        }
        List<Long> blogIds = new ArrayList<>(typedTuples.size());//博文id集合
        long minTimeStamp = 0;//记录最小的时间戳
        StringBuilder blogIdStr = new StringBuilder();//拼接博文id的字符串
        /*也记录上一条消息的时间戳*/
        int newOffset = 1; // 记录新的offset,至少为1,因为下一次查询是从这次查询的最后一条消息的下一条消息开始查询
        /*2*/
        //4.解析数据: blogId和minTimeStamp和offset
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {/* 5 4 4 3 3 3 2 2 */
            Long blogId = Long.valueOf(Objects.requireNonNull(typedTuple.getValue()));
            blogIds.add(blogId);//blogId
            /*博文id*/
            long timeStamp = Objects.requireNonNull(typedTuple.getScore()).longValue();//timeStamp
            /*博文发布时间戳*/
            //读取zset返回的set集合是一个排序集合,按时间戳从大到小排序,所以取最后一个就是最小的时间戳
            if (timeStamp == minTimeStamp) {
                //如果当前消息的时间戳等于上一条消息记录的最新时间戳,则说明这条消息是重复的,偏移量+1
                newOffset++;
                /*有多个相同时间戳的消息,则偏移量+1*/
            } else {
                //如果当前消息的时间戳不等于上一条消息记录的最新时间戳,则说明这条消息是新的,记录最小的时间戳和新的偏移量
                minTimeStamp = timeStamp;//记录最小的时间戳
                newOffset = 1;//刷新新的偏移量
            }
            //拼接博文id"5,4,4,3,3,3,2,2"
            if (blogIdStr.isEmpty()) {
                blogIdStr.append(blogId);
            }
            blogIdStr.append(",").append(blogId);
        }
        //如果最小时间戳等于最大时间戳,则说明这次查询的所有信息时间戳和上次查询的最小时间戳是相同的,则偏移量应该加上上次查询的偏移量
        newOffset = minTimeStamp == maxTimeStamp ? newOffset : newOffset + offset;
        //5.根据blogIds查询blog
        List<Blog> blogs = query().in("id", blogIds).last("ORDER BY FIELD(id, " + blogIdStr.toString() + ")").list();
        //6. 查询博客用户信息并设置到博客对象中,查询blog是否被当前登录用户点赞,设置到博客对象中
        for (Blog blog : blogs) {
            // 6.1 查询用户信息并设置到博客对象中
            User user = userService.getById(blog.getUserId());
            if (user == null) {
                log.error("用户不存在：userId={}", blog.getUserId());
                return Result.fail("用户不存在");
            }
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            // 6.2 查询blog是否被当前登录用户点赞
            boolean isBlogLiked = isBlogLiked(blog);
            if (isBlogLiked) {
                // 将isLiked设置为true
                blog.setIsLike(true);
            } else {
                // 将isLiked设置为false
                blog.setIsLike(false);
            }
        }
        //封装返回结果
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(newOffset);
        scrollResult.setMinTime(minTimeStamp);
        //6.响应结果
        return Result.ok(scrollResult);
    }


    private boolean isBlogLiked(Blog blog) {
        //获取当前登录用户id
        Long currentUserId = getCurrentUserId();

        //基于redis的set集合判断用户是否已经点赞
        String key = BLOG_LIKED_KEY + "_" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, currentUserId.toString());
        return score != null;
    }

    // 辅助方法：对敏感信息进行脱敏处理
    private String maskId(Long id) {
        return id == null ? "null" : "****" + id.toString().substring(Math.max(0, id.toString().length() - 4));
    }
}
